<?php

//对接文档 http://119.91.110.114/sakura/usmtaskadmin/file/tel.pdf
include_once "baseChannel.php";
// 时间相差8小时
date_default_timezone_set("Asia/Shanghai");
class super extends BaseChannel
{

    protected $token;
    protected $private_key;  //提单私钥
    protected $callback_public_key; //回调公钥


    public function __construct($options)
    {
        parent::__construct($options);
        $this->token = $options['token'];
        $this->callback_public_key = "-----BEGIN PUBLIC KEY-----\n" . $options['callback_public_key'] . "\n-----END PUBLIC KEY-----";
        $this->private_key = "-----BEGIN PRIVATE KEY-----\n" . $options['private_key'] . "\n-----END PRIVATE KEY-----";
    }
    // 计算签名提单需要签名  emptyWithSign 为空参与签名
    public function getSign($data, $emptyWithSign = false)
    {
        // foreach ($data as $key => $val) {
        //     if (!$emptyWithSign) {
        //         if (empty($val)) {
        //             unset($data[$key]);
        //         }
        //     }
        //     if (isset($data['sign'])) {
        //         unset($data['sign']);
        //     }
        // }
        // ksort($data);
        // $data['key'] = $this->appSecret;
        // // var_dump(111);
        // // var_dump($data);
        // $str = http_build_query($data);
        // $str = urldecode($str);
        // $sign = md5($str);
        // return $sign;
    }
    public function queryBalance($params = [])
    {

        return [
            'error' => 1,
            'msg' => '不支持查询',
            'code' => 500
        ];
    }
    //params :{push_order_sn:''} 
    public function queryOrder($params)
    {
        $data['act'] = 'act';
        $data['out_trade_no'] = $params['push_order_sn'];

        $url = $this->query_order_url . '?' . http_build_query($data);
        $return_str = $this->httpRequest($url, 'GET');
        $return_data = json_decode($return_str, 1);
        $ret = [
            'error' => 0,
            'order_status' => 2,
            'msg' => '初始化',
            'pz' => '', //凭证
            'post_data' => $data, //提交字符串
            'channel_data' => $return_str, //返回字符串
            'code' => 200
        ];
        $status = $return_data['data'][0]['states'];
        //处理中
        if ($return_data['code'] == 1 && $status == "充值中") {
            $ret['msg'] = '充值中';
        }
        // 成功
        if ($return_data['code'] == 1 && $status == "充值成功") {
            $ret['order_status'] = self::OrderSuccess;
            $ret['msg'] = '查询充值完成:' . $return_data['msg'];
        }
        // 失败
        if ($return_data['code'] == 1 && $status == "充值失败") {
            $ret['order_status'] = self::OrderFail;
            $ret['msg'] = '查询充值失败:' . $return_data['msg'];
        }
        return $ret;
    }
    public function submitOrder($mobile, $code, $params = [])
    {
        $data = [];
        $data['token'] = $this->token;
        $data['phone'] = $mobile;
        $data['out_trade_no'] = $params['push_order_sn'];
        $data['amount'] = $params['face_value'];

        if ($params['hf_type'] == 1) {
            // 1快充2慢充
            $timeout = 60 * 24; //快充一天
            // $timeout = 180;
        } else {
            // 慢充 默认24小时可以是倍数调整数值1即可
            $timeout = 60 * 24 * 3;
        }
        $data['lock_time'] = $timeout;

        $data['callback_url'] = $this->callback_url;

        // $signStr = $data['mchid'] . $data['tel'] . $data['price'] . $data['orderid']  . $data['teltype'] . $data['timeout'] . $data['notify'] . $data['time'] . $data['rand'] . $this->appSecret;
        $signStr = $data['out_trade_no'] . $data['phone'] . $data['amount'];
        $data['sign'] = $this->submitSign($signStr);
        // var_dump("请求参数");
        // var_dump($data);
        $url = $this->submit_order_url . "?" . http_build_query($data);
        $return_str = $this->httpRequest($url, 'GET', $data);
        $return_data = json_decode($return_str, 1);
        $ret = [
            'url' => $this->submit_order_url,
            'error' => -1,
            'msg' => '初始化',
            'channel_order' => $return_data['data']['orderId'] ?? '',
            'post_data' => json_encode($data),
            'channel_data' => $return_str,
            'code' => 200,
            'channel_order_price' =>  null,
            'channel_balance' => null,
        ];
        if ($return_data['code'] == 1) {
            $ret['error'] = 0;
            $ret['msg'] = $return_data['msg'] ?? '下单成功';
        } else {
            if (isset($return_data['code'])) {
                $ret['error'] = 1;
                $ret['code'] = 500;
                $ret['msg'] = $return_data['msg'] ?? '下单失败';
            }
        }
        return $ret;
    }
    public function callback($params)
    {
        // var_dump($params);

        $this->callback_params = $params;
        $sign = $params['sign'];
        $params = $params['data'];
        //  $params['out_order_id']
        $this->channel_order_sn = $params['orderId'];
        $this->push_order_sn = $params['out_trade_no'];
        //返回参数
        $res = $this->initCallBackParam();

        //订单状态
        $order_status = $params['payStatus'];
        $msg = null;
        //凭证
        // 2023031719401468490786515014_2023031722001448541436483108
        $arr = [];
        if ($params['tradeNO']) {
            $arr = explode('_', $params['tradeNO']);
        }
        if (count($arr) && $arr[1]) {
            $pz =  $arr[1];
        } else {
            $pz =  "";
        }

        $res['voucher'] = $pz;
        // 验证签名
        // $sign = $this->getSign($params);
        $signStr = $params['out_trade_no'] . $params['payStatus'] . $params['mobile'] . $params['payAmount'];
        // $signStr = urldecode($signStr);
        // var_dump($signStr);
        $signRes = $this->cbSign($signStr, $sign);
        if (!$signRes) {
            $res['error'] = 1;
            $res['msg'] = '签名不匹配';
            $res['resp_data'] = 'fail';
            $res['sign'] = $sign;
            return $res;
        }
        if ($order_status == "充值成功") {
            $res['order_status'] = self::OrderSuccess;
            $res['msg'] = $msg ?? '充值完成';
            $res['resp_data'] = 'ok';
        }

        if ($order_status == '充值失败') {
            $res['order_status'] = self::OrderFail;
            $res['msg'] = $msg ?? '充值失败';
        }
        return $res;
    }
    //获取当前时间的毫秒
    public function msectime()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }
    // 获取当前时间包括毫秒
    public function getCurDate($isSecond = false)
    {
        if ($isSecond) {
            return time();
        } else {
            $time = $this->msectime();
            $timestamp = time() . substr($time, -3);
            return $timestamp;
        }
    }
    function cbSign($data, $sign)
    {
        $cbKey = $this->callback_public_key;
        $ok =  openssl_verify($data, base64_decode($sign), $cbKey);
        return $ok;
    }
    function submitSign($data)
    {
        $data = urldecode($data);
        $rsa_public = $this->private_key;  //提单私钥

        openssl_sign($data, $signStr, $rsa_public);
        $encrypted = base64_encode($signStr);
        return $encrypted;
    }
}
